/*
 * Reksio - Memory Map Editor
 * Copyright (C) 2023 CERN
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * In applying this licence, CERN does not waive the privileges and immunities
 * granted to it by virtue of its status as an Intergovernmental Organization or
 * submit itself to any jurisdiction.
 */

#ifndef FILEWATCHER_H
#define FILEWATCHER_H

#include <QFileSystemWatcher>
#include <QMultiHash>
#include <QDir>
#include <QMap>
#include <QTime>

class NodesModel;
class AttributesModel;
class FileWatcher : public QObject
{
    Q_OBJECT
public:
    explicit FileWatcher(QObject* parent);
    void watch(const QString& root_file, NodesModel* root);
    void ignoreNextSignalFromFile(const QString& file);
    void clear();

Q_SIGNALS:
    void attributesFileChanged(const QModelIndex& attribute_index);
    void rootChanged();

private Q_SLOTS:
    void fileChanged(const QString& path);

public Q_SLOTS:
    // inserted
    void attributeInserted(AttributesModel* model, const QModelIndex& parent, int first, int last);

    // changed
    void attributeChanged(const QModelIndex& index);
    // if removed, dont care, will be filtered in fileChanged
    void changeRootFile(const QString& root_file);
private:
    AttributesModel* getAttributesModel(const QModelIndex& index) const;
    QFileSystemWatcher* _watcher;
    QMultiHash<QString, QPersistentModelIndex> _watched_attributes;
    QDir _rootDir;
    QString _rootFile;
    QMap<QString, QTime> temp_blocked_files;
    const int block_timeout_msec = 200; // 0.2s
};

#endif // FILEWATCHER_H
